const partner = require('../model/partner')
const jwt = require('jsonwebtoken')
const { code } = require('../static/secret')

module.exports = {
  coldRecommend: async (ctx, next) => {
    const token = ctx.headers.authorization.split(' ')[1]
    const username = await jwt.verify(token, code).username
    const number = Math.random()
    const data = []
    let answer2 = null
    let answer = await partner.cold.find({ username: username, random: { $lte: number } }, ['partner'])
    if (answer.length === 0) {
      answer = await partner.cold.find({ username: username, random: { $gt: number } }, ['partner'])
    } else if (answer.length <= 5) {
      answer2 = await partner.cold.find(
        { username: username, random: { $gt: number } }, ['partner'])
    }
    while (answer.length === 0) {
      answer = await partner.cold.find({ username: username, random: { $lte: number } }, ['partner'])
      if (answer.length === 0) {
        answer = await partner.cold.find({ username: username, random: { $gt: number } }, ['partner'])
      }
    }
    for (const member of answer) {
      data.push(member.partner)
    }
    if (answer2 !== null) {
      for (const member of answer2) {
        data.push(member.partner)
      }
    }
    ctx.body = {
      status: 200,
      message: '返回冷启动推荐列表成功',
      data: data
    }
    await next()
  },
  recommend: async (ctx, next) => {
    const token = ctx.headers.authorization.split(' ')[1]
    const username = await jwt.verify(token, code).username
    const number = Math.random()
    const data = []
    let answer2 = null
    let answer = await partner.partner.find({ username: username, random: { $lte: number } }, ['partner'])
    if (answer.length === 0) {
      answer = await partner.partner.find({ username: username, random: { $gt: number } }, ['partner'])
    } else if (answer.length <= 5) {
      answer2 = await partner.cold.find(
        { username: username, random: { $gt: number } }, ['partner'])
    }
    for (const member of answer) {
      data.push(member.partner)
    }
    if (answer2 !== null) {
      for (const member of answer2) {
        data.push(member.partner)
      }
    }
    ctx.body = {
      status: 200,
      message: '返回推荐列表成功',
      data: data
    }
    if (data.length === 0) {
      ctx.body.status = 403
      ctx.body.message = '推荐伙伴成员为无'
    }
    await next()
  }
}
